﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace CPhoneRC
{
    class DBHelper
    {

        public static string str = "Data Source=SKY-20190902IUZ\\SHISONGPING;Initial Catalog=PhoneAdd;Integrated Security=True"; 
        //数据库连接对象
        public static SqlConnection Conn = null;
        public static SqlDataReader reader = null;

        //数据库缓存数据
        public static DataSet dataSet = new DataSet();
        //初始化数据库连接
        public static void InitConnection()
        {
            //如果对象不存在，则创建连接
            if (Conn == null)
                Conn = new SqlConnection(str);
            //如果连接对象关闭，则打开连接
            if (Conn.State == ConnectionState.Closed)
                Conn.Open();
            //如果连接中断，则重启连接
            if (Conn.State == ConnectionState.Broken)
            {
                Conn.Close();
                Conn.Open();
            }
        }
        //读取数据
        public static SqlDataReader GetDataRead(string sql)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sql, Conn);
            reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            return reader;
        }
        //查询，获取DataSet
        public static void GetDataSet(string sqlStr)
        {
            InitConnection();
            DataSet ds = new DataSet();
            SqlDataAdapter dap = new SqlDataAdapter(sqlStr, Conn);
            dap.Fill(ds);
            Conn.Close();
        }

        //查询，获取DataTable
        public static DataTable SqlDataAdapter(string sqlStr)
        {
            InitConnection();
            DataTable table = new DataTable();
            SqlDataAdapter adapter = new SqlDataAdapter(sqlStr, Conn);
            adapter.Fill(table);
            Conn.Close();
            return table;
        }
        //增删改
        public static bool ExecuteNonQuery(string sql)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sql, Conn);
            int result = cmd.ExecuteNonQuery();
            Conn.Close();
            return result > 0;
        }
        //执行聚合函数
        public static object ExecuteScalar(string sqlStr)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sqlStr, Conn);
            object result = cmd.ExecuteScalar();
            Conn.Close();
            return result;
        }
    }
}
